﻿import pygame
import sys
import random
import time
from pygame.locals import *

# 初始化 Pygame
pygame.init()

# 游戏常量
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
GRID_SIZE = 20
GRID_WIDTH = WINDOW_WIDTH // GRID_SIZE
GRID_HEIGHT = WINDOW_HEIGHT // GRID_SIZE
FPS = 10

# 方向常量
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)

# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
DARK_GREEN = (0, 100, 0)
GRAY = (100, 100, 100)
YELLOW = (255, 255, 0)
PURPLE = (128, 0, 128)

# 创建游戏窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇游戏')
clock = pygame.time.Clock()

# 加载字体
font = pygame.font.Font(None, 36)
small_font = pygame.font.Font(None, 24)

class Snake:
    def __init__(self):
        self.positions = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
        self.direction = RIGHT
        self.next_direction = RIGHT
        self.grow = False
        self.color = GREEN
        self.head_color = DARK_GREEN
        self.score = 0
        self.speed = FPS
        self.last_move_time = 0
    
    def get_head_position(self):
        return self.positions[0]
    
    def update(self):
        # 更新方向
        self.direction = self.next_direction
        
        # 获取头部位置
        head = self.get_head_position()
        
        # 计算新的头部位置
        new_x = (head[0] + self.direction[0]) % GRID_WIDTH
        new_y = (head[1] + self.direction[1]) % GRID_HEIGHT
        new_head = (new_x, new_y)
        
        # 检查是否撞到自己
        if new_head in self.positions[1:]:
            return False  # 游戏结束
        
        # 添加新的头部
        self.positions.insert(0, new_head)
        
        # 如果不需要增长，则移除尾部
        if not self.grow:
            self.positions.pop()
        else:
            self.grow = False
            self.score += 10
            # 每得100分增加速度
            if self.score % 100 == 0:
                self.speed += 1
        
        return True  # 游戏继续
    
    def change_direction(self, direction):
        # 防止直接反向移动
        if (direction[0] * -1, direction[1] * -1) != self.direction:
            self.next_direction = direction
    
    def grow_snake(self):
        self.grow = True
    
    def draw(self, surface):
        for i, pos in enumerate(self.positions):
            # 绘制蛇身
            rect = pygame.Rect((pos[0] * GRID_SIZE, pos[1] * GRID_SIZE), 
                              (GRID_SIZE, GRID_SIZE))
            
            # 头部使用不同颜色
            if i == 0:
                pygame.draw.rect(surface, self.head_color, rect)
                pygame.draw.rect(surface, BLACK, rect, 1)
                
                # 绘制眼睛
                eye_size = GRID_SIZE // 5
                eye_offset = GRID_SIZE // 4
                
                # 根据方向确定眼睛位置
                if self.direction == UP:
                    left_eye = (rect.left + eye_offset, rect.top + eye_offset)
                    right_eye = (rect.right - eye_offset - eye_size, rect.top + eye_offset)
                elif self.direction == DOWN:
                    left_eye = (rect.left + eye_offset, rect.bottom - eye_offset - eye_size)
                    right_eye = (rect.right - eye_offset - eye_size, rect.bottom - eye_offset - eye_size)
                elif self.direction == LEFT:
                    left_eye = (rect.left + eye_offset, rect.top + eye_offset)
                    right_eye = (rect.left + eye_offset, rect.bottom - eye_offset - eye_size)
                else:  # RIGHT
                    left_eye = (rect.right - eye_offset - eye_size, rect.top + eye_offset)
                    right_eye = (rect.right - eye_offset - eye_size, rect.bottom - eye_offset - eye_size)
                
                pygame.draw.rect(surface, BLACK, pygame.Rect(left_eye, (eye_size, eye_size)))
                pygame.draw.rect(surface, BLACK, pygame.Rect(right_eye, (eye_size, eye_size)))
            else:
                pygame.draw.rect(surface, self.color, rect)
                pygame.draw.rect(surface, BLACK, rect, 1)

class Food:
    def __init__(self):
        self.position = (0, 0)
        self.color = RED
        self.randomize_position()
        self.type = 'normal'  # 'normal' 或 'special'
        self.special_timer = 0
        self.special_duration = 5000  # 5秒
    
    def randomize_position(self, snake_positions=None):
        if snake_positions is None:
            snake_positions = []
        
        # 生成不在蛇身上的随机位置
        while True:
            self.position = (random.randint(0, GRID_WIDTH - 1), 
                            random.randint(0, GRID_HEIGHT - 1))
            if self.position not in snake_positions:
                break
        
        # 随机决定是否为特殊食物 (10% 概率)
        if random.random() < 0.1:
            self.type = 'special'
            self.color = PURPLE
            self.special_timer = pygame.time.get_ticks()
        else:
            self.type = 'normal'
            self.color = RED
    
    def update(self):
        # 检查特殊食物是否过期
        if self.type == 'special' and pygame.time.get_ticks() - self.special_timer > self.special_duration:
            self.type = 'normal'
            self.color = RED
    
    def draw(self, surface):
        rect = pygame.Rect((self.position[0] * GRID_SIZE, self.position[1] * GRID_SIZE), 
                          (GRID_SIZE, GRID_SIZE))
        pygame.draw.rect(surface, self.color, rect)
        pygame.draw.rect(surface, BLACK, rect, 1)
        
        # 如果是特殊食物，绘制闪烁效果
        if self.type == 'special':
            if (pygame.time.get_ticks() // 200) % 2 == 0:
                inner_rect = pygame.Rect((self.position[0] * GRID_SIZE + GRID_SIZE//4, 
                                        self.position[1] * GRID_SIZE + GRID_SIZE//4), 
                                       (GRID_SIZE//2, GRID_SIZE//2))
                pygame.draw.rect(surface, YELLOW, inner_rect)

class Game:
    def __init__(self):
        self.snake = Snake()
        self.food = Food()
        self.game_over = False
        self.paused = False
        self.grid_color = GRAY
        self.background_color = BLACK
    
    def update(self):
        if self.paused or self.game_over:
            return
        
        # 更新食物
        self.food.update()
        
        # 更新蛇的位置
        if not self.snake.update():
            self.game_over = True
            return
        
        # 检查是否吃到食物
        if self.snake.get_head_position() == self.food.position:
            self.snake.grow_snake()
            # 根据食物类型给予不同分数
            if self.food.type == 'special':
                self.snake.score += 50
            self.food.randomize_position(self.snake.positions)
    
    def draw(self, surface):
        # 绘制背景
        surface.fill(self.background_color)
        
        # 绘制网格
        for x in range(0, WINDOW_WIDTH, GRID_SIZE):
            pygame.draw.line(surface, self.grid_color, (x, 0), (x, WINDOW_HEIGHT))
        for y in range(0, WINDOW_HEIGHT, GRID_SIZE):
            pygame.draw.line(surface, self.grid_color, (0, y), (WINDOW_WIDTH, y))
        
        # 绘制蛇和食物
        self.snake.draw(surface)
        self.food.draw(surface)
        
        # 绘制分数
        score_text = font.render(f'分数: {self.snake.score}', True, WHITE)
        surface.blit(score_text, (10, 10))
        
        # 绘制速度
        speed_text = small_font.render(f'速度: {self.snake.speed}', True, WHITE)
        surface.blit(speed_text, (10, 50))
        
        # 如果游戏暂停，显示暂停信息
        if self.paused:
            pause_text = font.render('游戏暂停 - 按P继续', True, WHITE)
            text_rect = pause_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2))
            surface.blit(pause_text, text_rect)
        
        # 如果游戏结束，显示游戏结束信息
        if self.game_over:
            game_over_text = font.render('游戏结束!', True, RED)
            restart_text = font.render('按R重新开始', True, WHITE)
            final_score_text = font.render(f'最终分数: {self.snake.score}', True, WHITE)
            
            game_over_rect = game_over_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2 - 50))
            restart_rect = restart_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2))
            score_rect = final_score_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2 + 50))
            
            surface.blit(game_over_text, game_over_rect)
            surface.blit(restart_text, restart_rect)
            surface.blit(final_score_text, score_rect)
    
    def handle_keys(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_p:
                    self.paused = not self.paused
                elif event.key == K_r and self.game_over:
                    self.__init__()  # 重置游戏
                elif not self.paused and not self.game_over:
                    if event.key == K_UP:
                        self.snake.change_direction(UP)
                    elif event.key == K_DOWN:
                        self.snake.change_direction(DOWN)
                    elif event.key == K_LEFT:
                        self.snake.change_direction(LEFT)
                    elif event.key == K_RIGHT:
                        self.snake.change_direction(RIGHT)
    
    def run(self):
        # 游戏主循环
        while True:
            self.handle_keys()
            self.update()
            self.draw(screen)
            pygame.display.update()
            clock.tick(self.snake.speed)

# 显示开始界面
def show_start_screen():
    screen.fill(BLACK)
    title_text = font.render('贪吃蛇游戏', True, GREEN)
    start_text = font.render('按任意键开始', True, WHITE)
    controls_text = small_font.render('方向键控制移动，P键暂停，R键重新开始', True, WHITE)
    
    title_rect = title_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2 - 50))
    start_rect = start_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2 + 20))
    controls_rect = controls_text.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2 + 70))
    
    screen.blit(title_text, title_rect)
    screen.blit(start_text, start_rect)
    screen.blit(controls_text, controls_rect)
    pygame.display.update()
    
    # 等待用户按键
    waiting = True
    while waiting:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                waiting = False

# 主函数
def main():
    # 显示开始界面
    show_start_screen()
    
    # 创建并运行游戏
    game = Game()
    game.run()

if __name__ == "__main__":
    main()